package cc.ufinity.networkdiagnose.view;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageNum;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.test.Location;
import cc.ufinity.networkdiagnose.widget.PingConfigWidget;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

@SuppressLint({ "HandlerLeak", "HandlerLeak" })
public class EnvironmentActivity extends Activity{
	private int gpsOrNet = LocationClientOption.GpsFirst;
	public static LocationClient mLocClient;
	//private LinearLayout phoneLayout;
	private WlanManager wlanManager;
	private TextView addressText;
	private ListView cmccList;
	private TextView netWorkDate;
	private Handler handler;
	private TelManager tm;
	private SimpleAdapter adapter;
	private TextView headTitle;
	private Button btback;
	
	private SensorManager sensorManager; 
    private Vibrator vibrator; 
    
    private static final String TAG = "EnvironmentActivity"; 
    private static final int SENSOR_SHAKE = 10; 
    private boolean isGetJWDEnd=false;
    private boolean isGetWifiListEnd=false;
    private Dialog dialog;
    private boolean isStart=false;
    private DBManager db;
    SharedPreferences settings;
    SharedPreferences.Editor editor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.environmentalinformation);
		addressText=(TextView)findViewById(R.id.geographicAddress);
		cmccList=(ListView)findViewById(R.id.cmccList);
		netWorkDate=(TextView)findViewById(R.id.networkDate);
		wlanManager = new WlanManager(EnvironmentActivity.this);
		
		db=DBManager.getInstance(EnvironmentActivity.this);
		 sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
	        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 
		
		btback = (Button)findViewById(R.id.btn_httpcfg_back);
		btback.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				EnvironmentActivity.this.finish();
			}
			
		});
		
		headTitle=(TextView)findViewById(R.id.head_title33);
		//phoneLayout = (LinearLayout)findViewById(R.id.networkDate);
		
		
		 settings = this.getSharedPreferences("REFRESH", 0);
         editor = settings.edit();
         
         
        
		
		handler=new Handler(){

			public void handleMessage(Message msg) {
				switch(msg.what){
				case 1:
					addressText.setText("经度 ："+GlobalApp.longitude+"\n纬度  :  "+GlobalApp.latitude);
					try{
						if(mLocClient.isStarted()){
							mLocClient.stop();
							isGetJWDEnd=true;
						}
					}catch(Exception e){}
					Toast.makeText(EnvironmentActivity.this, "经纬度刷新完毕", Toast.LENGTH_SHORT).show();
					break;
				case MessageWhat.WIFI_RECEIVE_LIST:
					updateWifi();
					isGetWifiListEnd=true;
					Toast.makeText(EnvironmentActivity.this, "WIFI列表刷新完毕", Toast.LENGTH_SHORT).show();
					break;
				case MessageWhat.TEL_STATE_SUCCESS:
					updateTel();    
					break;
				 case SENSOR_SHAKE: 
					  /*editor.putString("REFRESH", "1");
				        editor.commit();*/
					 if(Integer.parseInt(settings.getString("REFRESH", ""))>10000){
						 Toast.makeText(EnvironmentActivity.this, "累计次数已经超过10000次，请清除", Toast.LENGTH_SHORT).show();
						 break;
					 }
					 vibrator.vibrate(200); 
	                 writeToSDcardFile("message.xml",getContent());
	                  
	                  editor.putString("REFRESH", Integer.parseInt(settings.getString("REFRESH", ""))+1+"");
	                  editor.commit();
		                //Toast.makeText(EnvironmentActivity.this, "检测到摇晃，执行操作！", Toast.LENGTH_SHORT).show();
					 showRefreshDialog();
					try{
						 if (sensorManager != null) {//刷新期间  取消监听器 
					            sensorManager.unregisterListener(sensorEventListener); 
					        }
						mLocClient.start();//重新打开
						start();//开始扫描
					}catch(Exception e){
						Log.i(TAG, "刷新失败"); 
					}
					new Thread(){
						public void run(){
							while(!isStart){
								if(isGetJWDEnd&&isGetWifiListEnd){
									if(dialog!=null){
										dialog.dismiss();
									}
									 if (sensorManager != null) {// 注册监听器 
								            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); 
								            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率 
								        } 
									 isStart=true;
									 isGetJWDEnd=false;
									 isGetWifiListEnd=false;
								}
							}
						}
					}.start();
		         break; 
				}
			}
		};
		
		if(GlobalApp.longitude.equals("0.0")&&GlobalApp.latitude.equals("0.0")){
			Location loc=new Location(getApplicationContext(),handler);
			mLocClient=loc.mLocationClient;
			setLocationOption();
			mLocClient.start();
		}else{
			addressText.setText("经度 ："+GlobalApp.longitude+"\n纬度  :  "+GlobalApp.latitude);
		}
		
		tm = new TelManager(this);
		tm.setHandler(handler);
		wlanManager.setHandler(handler);
		start();
		
		String Number = settings.getString("REFRESH", "");
        if(Number.equals("") || Number.equals(null)){
        	 writeToSDcardFile("message.xml","<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>");
	        editor.putString("REFRESH", "1");
	        editor.commit();
        }
	}
	
	public void showRefreshDialog(){
		dialog = new Dialog(EnvironmentActivity.this,R.style.REFRESH);
		dialog.setContentView(R.layout.refresh);
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	public String getContent(){
		StringBuffer sb=new StringBuffer(); 
		sb.append("<environment>\n").append("<longitude>").append(GlobalApp.longitude).append("</longitude>").append("\n").
		append("<latitude>").append(GlobalApp.latitude).append("</latitude>").append("\n").
		append("<netWorkType>").append(tm.getNetworkType()).append("</netWorkType>").append("\n").
		append("<SignalStrength>").append(tm.getSignalStrength()).append("</SignalStrength>").append("\n").
		append("<Lac>").append(tm.getLac()).append("</Lac>").append("\n").
		append("<Ci>").append(tm.getCI()).append("</Ci>").append("\n").
		append("<wifiLists>").append("\n");
		if(wlanManager!=null&&wlanManager.getWifiList()!=null&&wlanManager.getWifiList().size()>0){
			for(int i=0;i<wlanManager.getWifiList().size();i++){
				sb.append("<wifi>").append("\n").
				append("<wifiName>").append(wlanManager.getWifiList().get(i).get("ssid")).append("</wifiName>").append("\n").
				append("<MAC>").append(wlanManager.getWifiList().get(i).get("mac")).append("</MAC>").append("\n").
				append("<WifiSignalStrength>").append(wlanManager.getWifiList().get(i).get("level")).append("</WifiSignalStrength>").append("\n").
				append("<channel>").append(wlanManager.getWifiList().get(i).get("xindao")).append("</channel>").append("\n").
				append("</wifi>").append("\n");
			}
		}
		sb.append("</wifiLists>").append("\n").append("</environment>");
		return sb.toString();
	}
	
	
	  @Override 
	    protected void onResume() { 
	    	System.out.println("--------正在注册监听手机是否摇一摇-----");
	        super.onResume(); 
	        if (sensorManager != null) {// 注册监听器 
	            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); 
	            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率 
	        } 
	    } 
	    
	    @Override 
	    protected void onStop() { 
	    	System.out.println("--------取消监听手机是否摇一摇-----");
	        super.onStop(); 
	        if (sensorManager != null) {// 取消监听器 
	            sensorManager.unregisterListener(sensorEventListener); 
	        } 
	    } 
	    
	    
	    /**
	     * 重力感应监听
	     */ 
	    private SensorEventListener sensorEventListener = new SensorEventListener() { 
	 
	        public void onSensorChanged(SensorEvent event) { 
	            // 传感器信息改变时执行该方法 
	            float[] values = event.values; 
	            float x = values[0]; // x轴方向的重力加速度，向右为正 
	            float y = values[1]; // y轴方向的重力加速度，向前为正 
	            float z = values[2]; // z轴方向的重力加速度，向上为正 
	         //  Log.i(TAG, "x轴方向的重力加速度" + x +  "；y轴方向的重力加速度" + y +  "；z轴方向的重力加速度" + z); 
	            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。 
	            int medumValue = 19;// 三星 i9250怎么晃都不会超过20，没办法，只设置19了 
	            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) { 
	                Message msg = new Message(); 
	                msg.what = SENSOR_SHAKE; 
	                handler.sendMessage(msg); 
	            } 
	        } 
	        @Override 
	        public void onAccuracyChanged(Sensor sensor, int accuracy) { 
	 
	        } 
	    }; 
	
	
	private void updateTel() {
		if(tm.getNetworkType().equals("EDGE") || tm.getNetworkType().equals("GPRS")){
			headTitle.setText("GSM网络");
		} else if(tm.getNetworkType().equals("HSDPA") || tm.getNetworkType().equals("HSUPA")){
			headTitle.setText("TD网络");
		}
		netWorkDate.setText("网络类型: " + tm.getNetworkType()+
				"\n信号强度: " + tm.getStrSignalStrength()+" dBm"
				+"\nLAC: " + tm.getLac() 
				+"\nCI: " + tm.getCI());
	}

	private void updateWifi() {
		
		List<Map<String, Object>> data = wlanManager.getWifiList(); 
		if(data.size() > 0) {
			adapter = null;
			 adapter = new SimpleAdapter(this, data,
					R.layout.rssi_list_widget, new String[] { "ssid", "mac", "img",
							"level","xindao"}, new int[] { R.id.wifi_ssid, R.id.wifi_mac,
							R.id.wifi_img, R.id.wifi_level ,R.id.wifi_xindao});
			cmccList.setAdapter(adapter);
		}
	}
	
	/**
	 * 开始扫描周围的AP
	 */
	private void start() {
		new Thread(){
			public void run(){
				wlanManager.startScan();
			}
		}.start();
	}
	
	
	
	/**
	 * 获取的是经纬度所需要的参数的设置
	 */
	private void setLocationOption(){
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			 
		option.setCoorType("bd09ll");		 
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setScanSpan(2000); 
		option.setAddrType("all");  
		option.setPriority(gpsOrNet);        
//		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}
	 


	/**
	 *  //三个参数
    //第一个是文件名字
    //第二个是文件存放的目录
    //第三个是文件内容
	 * @param file
	 * @param destDirStr
	 * @param szOutText
	 */
	public void writeToSDcardFile(String fileName, String szOutText) {

		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		// 拥有可读可写权限

		try {
			// 获取扩展存储设备的文件目录
			File SDFile = android.os.Environment.getExternalStorageDirectory()
					.getAbsoluteFile();
			File destDir = new File(SDFile.getAbsolutePath() + "/" + "wirelessEnvironment");// 文件目录
			if (!destDir.exists()) {// 判断目录是否存在，不存在创建
				try {
					editor.putString("REFRESH", "");
				    editor.commit();
					destDir.mkdir();// 创建目录
				} catch (Exception e) {
					e.printStackTrace();
				}
			} 
			// 打开文件
			myFile = new File(destDir + File.separator + fileName);
			// 判断文件是否存在,不存在则创建
			if (!myFile.exists()) {
				myFile.createNewFile();// 创建文件
			}

			// 写数据 注意这里，两个参数，第一个是写入的文件，第二个是指是覆盖还是追加，
			// 默认是覆盖的，就是不写第二个参数，这里设置为true就是说不覆盖，是在后面追加。
			/*
			 * FileOutputStream outputStream = new
			 * FileOutputStream(myFile,true);
			 * outputStream.write(szOutText.getBytes());//写入内容
			 * outputStream.close();//关闭流
			 */
			FileWriter fw = null;
			BufferedWriter bw = null;
			String datetime = "";
			try {
				SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd"
						+ " " + "hh:mm:ss");
				datetime = tempDate.format(new java.util.Date()).toString();
				fw = new FileWriter(myFile, true);//
				// 创建FileWriter对象，用来写入字符流
				bw = new BufferedWriter(fw); // 将缓冲对文件的输出
				String myreadline = datetime + "[]" + szOutText;
				bw.write(myreadline + "\n"); // 写入文件
				bw.newLine();
				bw.flush(); // 刷新该流的缓冲
				bw.close();
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
				try {
					bw.close();
					fw.close();
				} catch (IOException e1) {
				}
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
	}
	
}
